import base64
import io
import os
import re
import time
from datetime import datetime

import requests
from flask import Blueprint, request, url_for, g, send_file, Response, send_from_directory, make_response
from sqlalchemy import text
from utils.ResponseResult import success_json_result, fail_json_result
from models.BookSystemModels import BookInfoModel, FileInfoModel
from models.ModelConvert import db_results_to_dict
from exts import db
from config import UPLOAD_FOLDER, UPLOAD_ENDPOINT, UPLOAD_BASE_FOLDER

bp = Blueprint("books_bp", __name__, url_prefix="/book")


@bp.route("/queryBooks1", methods=['POST'])
def queryBookList1():
    data = request.get_json()
    print(f"请求数据：{data}")
    book_no = data.get("bookNo")
    book_name = data.get("bookName")
    pageNo = data.get("pageNo", 1)
    pageSize = data.get("pageSize", 10)

    # 原生SQL构建
    sql = """
        select bi.id,bi.book_no,bi.book_name,bi.book_author,bi.type_id,bi.file_id,bi.create_date,
        bi.create_user,bi.update_date,bi.update_user,bi.version,bt.type_name,fi.file_url 
        from book_info bi
        left join book_type bt on bi.type_id = bt.type_id
        left join file_info fi on bi.file_id = fi.file_id
        where 1=1
    """
    # 查询总数
    count_sql = """
       select count(*) as totals
       from book_info bi
       left join book_type bt on bi.type_id = bt.type_id
       left join file_info fi on bi.file_id = fi.file_id
       where 1=1
   """
    # 查询条件
    query_params = {}
    if book_no:
        sql += " and bi.book_no = %s" % book_no
        count_sql += " and bi.book_no = %s" % book_no
        query_params["book_no"] = book_no
    if book_name:
        # 根据book_name模糊查询
        book_name = book_name.strip()
        sql += " and bi.book_name like %s" % book_name
        count_sql += " and bi.book_name like %s" % book_name
        query_params["book_name"] = "%{}%".format(book_name)
    # 排序，分页
    sql += " order by bi.create_date desc"
    sql += " limit %s,%s" % (pageSize * (pageNo - 1), pageSize)
    result = db.session.execute(text(sql), query_params).fetchall()
    # 总数
    totals = db.session.execute(text(count_sql), query_params).scalar()
    # 解析bookList
    db_result_list = db_results_to_dict(result)

    books = {
        "bookList": db_result_list,
        "totals": totals
    }
    print(f"结果：{books}")
    return success_json_result(data=books)


@bp.route("/queryBooks", methods=['POST'])
def queryBookList():
    data = request.get_json()
    book_no = data.get("bookNo")
    book_name = data.get("bookName")
    pageNo = data.get("pageNo", 1)
    pageSize = data.get("pageSize", 10)

    # 关联查询
    query = BookInfoModel.query
    if book_no:
        query = query.filter(BookInfoModel.book_no == book_no)
    if book_name:
        # 根据book_name模糊查询
        book_name = book_name.strip()
        query = query.filter(BookInfoModel.book_name.like("%{}%".format(book_name)))
    query = query.order_by(BookInfoModel.create_date.desc())
    pagination = query.paginate(page=pageNo, per_page=pageSize, error_out=False)
    bookList = pagination.items
    totals = pagination.total
    # 解析bookList
    results = []
    for item in bookList:
        results.append(
            {
                "id": item.id,
                "bookNo": item.book_no,
                "bookName": item.book_name,
                "bookAuthor": item.book_author,
                "typeId": item.type_id,
                "fileId": item.file_id,
                "createDate": item.create_date.strftime("%Y-%m-%d %H:%M:%S"),
                "createUser": item.create_user,
                "updateDate": item.update_date.strftime("%Y-%m-%d %H:%M:%S"),
                "updateUser": item.update_user,
                "version": item.version,
                "typeName": item.book_type.type_name,
                "fileUrl": getattr(item.file_info, "file_url", "")
            }
        )

    books = {
        "bookList": results,
        "totals": totals
    }
    return success_json_result(books)


@bp.route("/uploadBook", methods=['POST'])
def upload_book():
    try:
        bookNo = request.form.get("bookNo")
        bookName = request.form.get("bookName")
        bookAuthor = request.form.get("bookAuthor")
        bookAvatarFile = request.files.get("bookAvatar")
        fileName = bookAvatarFile.filename
        fileType = bookAvatarFile.mimetype
        newFileName = str(int(time.time())) + "_" + fileName

        # 上传文件
        saveFile = os.path.join(UPLOAD_FOLDER, newFileName)
        bookAvatarFile.save(saveFile)
        # _external=True返回绝对路径，否则返回相对路径（/static/uploads/xxx）
        file_url = url_for(UPLOAD_ENDPOINT, filename=f"{UPLOAD_BASE_FOLDER}/{newFileName}", _external=True)

        file_info = FileInfoModel(file_name=newFileName, file_type=fileType, file_url=file_url)
        db.session.add(file_info)
        db.session.commit()

        file_id = file_info.file_id
        # 保存书籍信息
        cur_user = getattr(g, "user")
        book_info = BookInfoModel(book_no=bookNo, book_name=bookName, book_author=bookAuthor, type_id=1,
                                  file_id=file_id, create_date=datetime.now(), create_user=cur_user.user_name,
                                  update_date=datetime.now(), update_user=cur_user.user_name, version=0)
        db.session.add(book_info)
        db.session.commit()

        return success_json_result(data=f"{file_url}", msg="书籍信息上传成功")
    except Exception as e:
        print(f"上传文件失败：{e}")
        return fail_json_result(msg=f"上传文件失败：{e}")


# def allowed_file(filename):
#     return '.' in filename and \
#            filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@bp.route("/downloadImage")
def download_image():
    url = request.args.get("fileUrl")
    # 下载模式 blob base64
    download_mode = request.args.get("downloadMode")
    if not url:
        return fail_json_result(msg="图片下载异常，图片地址不能为空")
    if not download_mode:
        download_mode = "blob"
    relative_url = "/".join(url.split("/")[3:])
    print(f"相对路径：{relative_url}")
    try:
        if download_mode == "blob":
            # 方法一
            # file_name = url.split("/")[-1]
            # return send_from_directory(UPLOAD_FOLDER, file_name, as_attachment=True)

            # 方法二
            # file_response = requests.get(url)
            # print(f"下载返回值：{file_response}")
            # return file_response

            # 方法三、将图片文件blob返回给客户端（常用）
            file_response = send_file(
                relative_url,
                as_attachment=True,
                mimetype='image/jpeg'
            )
            return file_response
        if download_mode == "base64":
            # 方案二、返回图片base64
            with open(relative_url, "rb") as f:
                image_data = f.read()
            image_base64 = base64.b64encode(image_data).decode('utf-8')
            result_data = {
                "imageBase64": image_base64,
                "fileName": relative_url.split("/")[-1]
            }
            return success_json_result(data=result_data)
    except Exception as e:
        return fail_json_result(msg=f"图片下载失败：{e}")


@bp.route("/downloadTest")
def downloadTest():
    # response = send_from_directory(UPLOAD_FOLDER, "1729756329_planetDocs1.jpg", as_attachment=True)
    response = send_file('static/uploads/1729756329_planetDocs1.jpg', as_attachment=True, download_name='xxx.jpg')
    # response.headers.add('Content-Disposition', 'attachment; filename="xxxx.jpg"')
    return response
